package cn.touna.jss.modules.custom.education;

import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.custom.education.entity.EducationRequest;
import cn.touna.jss.modules.third.pengyuan.PengyuanService;
import cn.touna.jss.modules.third.pengyuan.entity.PengyuanEducationRequest;
import cn.touna.risk.api.domain.Response;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * \* User: MeiZhongHao
 * \* Date: 2018-08-28
 * \* Time: 14:05
 * \* Description: 查询学历接口
 * \
 */
@Service
public class EducationService {

    @Autowired
    private PengyuanService pengyuanService;

    private final static String rgex = "([1-9]\\d*\\.*\\d*|0\\.\\d*[1-9]\\d*)\\-([1-9]\\d*\\.*\\d*|0\\.\\d*[1-9]\\d*)";

    private static final Logger logger = LogManager.getLogger(EducationService.class);

    @ApiMapping(value = "education.getEducation",desc = "复合接口.学历信息（鹏元/优分）")
    public Response queryEducation(EducationRequest request) {
        Response response = null;
        // 查询鹏元个人偿贷能力接口
        Map<String, Object> data = new HashMap<>();
        try {
            PengyuanEducationRequest py = new PengyuanEducationRequest();
            py.setQueryReasonID(request.getQueryReasonID());
            py.setIdCard(request.getIdCard());
            py.setMobile(request.getMobile());
            py.setName(request.getName());
            response = pengyuanService.queryEducation(py);
            String[] edu = pengyuanTranslate(response);
            Map<String, Object> product = new HashedMap();
            Map<String, Object> eduInfo = new HashedMap();
            data.put("product", product);
            product.put("eduInfo", eduInfo);
            eduInfo.put("educationDegree", edu[0]);
            eduInfo.put("keycllgunvsts", edu[1]);
            response.setData(data);
        } catch (Exception e) {
            logger.warn("find education by pengyuan error : {}", e.getLocalizedMessage());
        } finally {
        }
        // set reponse
        return response;
    }

    public static String[] pengyuanTranslate(Response response) {
//        String education = null;
        String education[] = new String[2];
        try {
            if (null != response) {
                logger.info(response.getData());
                // transform
                JSONObject data = (JSONObject) response.getData();
                if (null != data) {
                    JSONObject cisReports = data.getJSONObject("cisReports");
                    if (null != cisReports) {
                        JSONObject cisReport = cisReports.getJSONObject("cisReport");
                        if (null != cisReport) {
                            JSONObject personDebtPayingAbilityEvaluate = cisReport.getJSONObject("personDebtPayingAbilityEvaluate");
                            if (null != personDebtPayingAbilityEvaluate) {
                                String evaluateResult = (String) personDebtPayingAbilityEvaluate.get("evaluateResult");
                                String str = match(evaluateResult, rgex, 0);
                                if (StringUtils.isNotEmpty(str)) {
                                    String[] limiter = str.split("\\-");
                                    if (limiter != null && limiter.length == 2) {
                                        Double x = Double.valueOf(limiter[0]);
                                        Double y = Double.valueOf(limiter[1]);
                                        //
                                        if (x != null && y != null) {
                                            x = x * 10000;
                                            y = y * 10000;
                                            if (x >= 100000 && x <= 115000) {
                                                // 硕士及以上
                                                education[0] = "1";
                                                if (y - x >= 81500) {
                                                    education[1] = "1";
                                                }
                                            } else if (x >= 60000 && x <= 75000) {
                                                // 本科
                                                education[0] = "2";
                                                if (y - x >= 61500) {
                                                    education[1] = "1";
                                                }
                                            } else if (x >= 40000 && x <= 55000) {
                                                // 专科
                                                education[0] = "3";
                                                if (y - x >= 61500) {
                                                    education[1] = "1";
                                                }
                                            } else if (x >= 20000 && x <= 35000) {
                                                // 无学历（高中及以下）
                                                education[0] = "4";
                                            } else if (x >= 0 && x <= 15000) {
                                                // 未查得
                                                education[0] = "5";
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.info("warn pengyuanTranslate : {}", e.getMessage());
        }
        if (StringUtils.isEmpty(education[0])) {
            // 未查得
            education[0] = "5";
        }
        if (StringUtils.isEmpty(education[1])) {
            // 未查得
            education[1] = "2";
        }
        return education;
    }

    public static String match(String str, String rgex, int i) {
        Pattern pet = Pattern.compile(rgex);
        Matcher match = pet.matcher(str);
        MatchResult ms = null;
        while (match.find()) {
            ms = match.toMatchResult();
        }
        if (ms==null)
            return null;
        return ms.group(i);
    }
}